package com.note7_12.question2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Question3 {

	/*
	 * 修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。
	 */

	public void updateProduct(int itemno, int stockcount) {
		String path = "src/com/note7_12/question2/products.xml";
		SAXReader reader = new SAXReader();
		XMLWriter xm = null;
		try {
			Document doc = reader.read(path);
			Element root = doc.getRootElement();
			List<Element> list = root.selectNodes("product");
			for (Element e : list) {
				// 返回xml中商品的编号
				int xmlItemno = Integer.valueOf(e.selectSingleNode("itemno").getText());
				if (xmlItemno == itemno) {
					e.element("stockcount").setText(String.valueOf(stockcount));
					break;
				}
			}
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			xm = new XMLWriter(new FileOutputStream(path), format);
			xm.write(doc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (xm != null) {
				try {
					xm.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
